package com.pcxt.net;

import java.io.*;
import java.net.URL;

import android.net.http.*;
import android.util.Log;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.*;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.*;
import com.pcxt.exception.*;

public class HttpConnectionProcessor {

	/*
	 * private variables
	 */
	private IHttpReceiver PARENT = null;
	//private String TARGET_URL = "";
	
	
	/*
	 * public method for network control
	 */
	
	
	
	public void getRemoteFileContents (String obid) throws XException {
		
		HttpResponse response = 
		connect (obid);
			PARENT.refreshData(response);

	}
	
	/*
	 * public methods for initialization
	 */
	
	public static HttpConnectionProcessor initialize(/*String targetURL,*/ IHttpReceiver parent) {
		HttpConnectionProcessor result = new HttpConnectionProcessor();
		
		result.setPARENT(parent);
		//result.setTARGET_URL(targetURL);
		
		return result;
	}
	
	
	private HttpResponse connect(String obid) throws XException {
		HttpPost post = PARENT.getParams(obid);
		try {
			
			HttpResponse response = null;
			/*
			URL url = new URL(TARGET_URL);
			HttpHost targetHost = new HttpHost(url.getHost(),80,"http");
			*/
			DefaultHttpClient client = new DefaultHttpClient();
			
			client.addRequestInterceptor(preemptiveAuth,0);
			client.getCredentialsProvider().setCredentials(new AuthScope(post.getURI().getHost()
					/*targetHost.getHostName()*/,post.getURI().getPort() /* targetHost.getPort()*/ ), 
					new UsernamePasswordCredentials(PARENT.getUserid(),PARENT.getPassword()));
			

		    
		    
		    
			
			
			response = client.execute(post);
			
			
			if (response.getStatusLine().getStatusCode() == 200) {
				// success
				return response;
			}
			else throw new XException ("Connection Failed:" + response.getStatusLine().getReasonPhrase());
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
			throw new XException (ioe.getMessage());
		}
	}
	
	
		HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
		    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
		        Log.d("Connection","Entering authorization..");
		        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
		        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
		                ClientContext.CREDS_PROVIDER);
		        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
		        
		        if (authState.getAuthScheme() == null) {
		            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
		            Credentials creds = credsProvider.getCredentials(authScope);
		            if (creds != null) {
		                authState.setAuthScheme(new BasicScheme());
		                authState.setCredentials(creds);
		            }
		        }
		        /*
		        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
		        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
		                ClientContext.CREDS_PROVIDER);
		        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
		        
		        if (authState.getAuthScheme() == null) {
		            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
		            Credentials creds = credsProvider.getCredentials(authScope);
		            if (creds != null) {
		                authState.setAuthScheme(new BasicScheme());
		                authState.setCredentials(creds);
		            }
		        }
		        */
		    }    
		};

	
	private HttpConnectionProcessor() {
		// TODO Auto-generated constructor stub
	}

/*

	public String getTARGET_URL() {
		return TARGET_URL;
	}



	public void setTARGET_URL(String tARGET_URL) {
		TARGET_URL = tARGET_URL;
	}

*/

	public void setPARENT(IHttpReceiver pARENT) {
		PARENT = pARENT;
	}

}
